﻿using System.Data.SqlClient;
using System.Messaging;
using System;

namespace SyncDBServer
{
    public class Connection
    {
        SqlConnection dbcon;
        MessageQueue log_queue;

        public Connection()
        {
            ServiceSettings settings = ServiceSettings.GetInstance();

            try
            {
                this.dbcon = new SqlConnection(settings.ConnectionString);
                this.dbcon.Open();
            }
            catch
            {
                this.dbcon = null;
            }

            try
            {
                this.log_queue = new MessageQueue(settings.LogQueue);
                this.log_queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            }
            catch
            {
                this.log_queue = null;
            }
        }

        public void Close()
        {
            if(this.dbcon != null) this.dbcon.Close();
        }

        public void Log(string Label, string Format, params object[] Args)
        {
            if (this.log_queue == null) return;

            Message msg = new Message(String.Format(Format, Args));
            this.log_queue.Send(msg, Label);
        }
    }
}
